package com.hmall.common.config;

import cn.hutool.core.collection.CollUtil;
import com.hmall.common.interceptor.UserInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * MVC配置类
 * 配置拦截器、路径映射等Web相关配置
 */
@Configuration
@EnableConfigurationProperties(AuthProperties.class)
@RequiredArgsConstructor
public class MvcConfig implements WebMvcConfigurer {
    
    @Autowired
    private AuthProperties authProperties;
    
    /**
     * 添加拦截器到Spring MVC配置中
     * @param registry 拦截器注册器
     */
    public void addInterceptors(InterceptorRegistry registry) {
        // 1.添加用户身份验证拦截器
        UserInterceptor loginInterceptor = new UserInterceptor();
        InterceptorRegistration registration = registry.addInterceptor(loginInterceptor);
        
        // 2.配置需要拦截的路径模式
        List<String> includePaths = authProperties.getIncludePaths();
        if (CollUtil.isNotEmpty(includePaths)) {
            registration.addPathPatterns(includePaths);
        }
        
        // 3.配置需要排除的路径模式（不进行拦截）
        List<String> excludePaths = authProperties.getExcludePaths();
        if (CollUtil.isNotEmpty(excludePaths)) {
            registration.excludePathPatterns(excludePaths);
        }
        
        // 4.默认排除一些常见的无需拦截的路径
        registration.excludePathPatterns(
                "/error",                    // 错误页面
                "/favicon.ico",              // 网站图标
                "/v2/**",                    // Swagger2 API路径
                "/v3/**",                    // Swagger3 API路径
                "/swagger-resources/**",     // Swagger资源路径
                "/webjars/**",               // WebJars静态资源
                "/doc.html"                  // 接口文档页面
        );
    }

}